#!/bin/sh /etc/rc.common

START=4
USE_PROCD=1

_setup_macaddr() {
	uci -q get "network.$1_dev.macaddr" >/dev/null && return
	uci -q set "network.$1_dev.macaddr=$2"
}

_save_macaddr() {
	local _ifname
	local _macaddr
	uci -q get "network.$1_dev.ifname" >/dev/null && {
		_ifname=$(uci -q get "network.$1.ifname")
		if [ -n "$(uci -q get network.$1.macaddr)" ] &&  [ "$(uci -q get network.$1.macaddr)" != "$(uci -q get network.$1_dev.macaddr)" ]; then
			uci -q set network.$1_dev.macaddr="$(uci -q get network.$1.macaddr)"
		else
			_macaddr=$(ip link show dev $_ifname 2>/dev/null | grep link | awk '{print $2}')
			[ -n "$_macaddr" ] && {
				uci -q set network.$1_dev.macaddr=$_macaddr
				uci -q set network.$1.macaddr=$_macaddr
			}
		fi
	}
	[ -z "$(uci -q get network.$1.macaddr)" ] && {
		_ifname=$(uci -q get "network.$1.ifname")
		[ -n "$_ifname" ] && {
			_macaddr=$(ip link show dev $_ifname 2>/dev/null | grep link | awk '{print $2}')
			[ -n "$_macaddr" ] && {
				uci -q set network.$1.macaddr=$_macaddr
			}
		}
	}
}

_delete_device() {
	[ "$(echo $1 | grep _dev)" != "" ] && {
		local _intfdev=$(echo $1 | sed 's/_dev//')
		[ "$(uci -q get network.$_intfdev.type)" != "macvlan" ] && {
			logger -t "macvlan" "$_intfdev type is not MacVLAN, remove device network.$1"
			uci -q batch <<-EOF
			delete network.$1
			commit network
			delete macvlan.$1
			commit macvlan
			EOF
		}
		return
	}
}


# Configuration by interface
_setup_interface() {
	local _ifname
	config_get _ifname "$1" masterintf
	[ -z "$_ifname" ] && return
	local _type
	config_get _type "$1" type
	config_get _proto "$1" proto
	[ "$_proto" = "macvlan" ] && _type="macvlan"
	[ "$_type" = "macvlan" ] || return 0

	uci -q get "network.$1_dev.ifname" >/dev/null && {
		uci -q set network.$1_dev.mtu=$(uci -q get network.$1.mtu)
		[ -z "$(uci -q get network.$1.masterintf)" ] && uci -q set network.$1.masterintf=$(uci -q get network.$1_dev.ifname)
		[ -n "$(uci -q get network.$1.masterintf)" ] && uci -q set network.$1_dev.ifname=$(uci -q get network.$1.masterintf)
		[ -z "$(uci -q get network.$1.macaddr)" ] && uci -q set network.$1_dev.macaddr=$(uci -q get network.$1.macaddr)
		uci set network.$1.ifname=$1
		uci -q commit network
		return 0
	}

	uci -q batch <<-EOF
	set network.$1_dev=device
	set network.$1_dev.name=$1
	set network.$1_dev.type=macvlan
	set network.$1_dev.ifname=$_ifname
	set network.$1.ifname=$1
	set network.$1.masterintf=$_ifname
	set network.$1.type=macvlan
	set network.$1.defaultroute=0
	EOF
	
	_macaddr=$(uci -q get "network.$1.macaddr")
	_setup_macaddr "$1" "${_macaddr:-auto$(date +%s)}"
	uci -q set network.$1_dev.mtu=$(uci -q get network.$1.mtu)
	uci -q commit network
}

start_service() {
	. /lib/functions.sh
	config_load network
	config_foreach _delete_device device
	config_foreach _setup_interface interface
	config_foreach _save_macaddr interface
	uci -q commit network
}

reload_service() {
	start
}

service_triggers() {
	procd_add_reload_trigger network
}
